package com.landray.kmss.sys.organization.webservice.in.main;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;

import com.landray.kmss.sys.organization.webservice.in.ISysSynchroSetOrgWebService;
import com.landray.kmss.sys.organization.webservice.in.SysSynchroSetOrgContext;
import com.landray.kmss.sys.organization.webservice.in.SysSynchroSetResult;
import com.oa.tools.utils.SecurityUtil;
import com.oa.tools.utils.StringUtil;

/**
 * WebService客户端
 * 
 */
public class OAWebServiceInClient {
	
	public static final String TYPE_ORG = "org";//org(机构)
	public static final String TYPE_DEP = "dept";//dept(部门)
	public static final String TYPE_GRP = "group";//group(群组)
	public static final String TYPE_POS = "post";//post(岗位)
	public static final String TYPE_PER = "person";//person(人员)
	
	private static final int OPTTYPE_ADD = 1;
	private static final int OPTTYPE_UPD = 2;
	private static final int OPTTYPE_DEL = 3;
	
	public static final String APPNAME="OA-TOOL";
	
	/**
	 * 主方法
	 * 
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		//updatePerson("111111", "9999","苏苏苏","F", "13811111111", "1234", "leaders");
		
		deletePerson("111111");
	}
	
	/**
	 * OA新增用户
	 * @param id			用户id，fd_import_info字段
	 * @param no			工号
	 * @param loginName		登陆名
	 * @param password		密码
	 * @param name			姓名
	 * @param mobile		手机
	 * @param tel			固话
	 * @param email			邮箱
	 * @param oa_dept_id	部门id 部门的fd_import_info字段
	 * @throws Exception
	 */
	public static void addPerson(String id,String no,String name,String gender,String loginName,String password,String mobile,String tel,String email,String oa_dept_id) throws Exception {
		

		OAOrg person = new OAOrg();
		person.type = TYPE_PER;
		person.id = id;
		person.name = name;
		person.sex=gender;
		person.mobileNo = mobile;
		person.workPhone = tel;
		person.parent = oa_dept_id;
		person.no = no;
		person.loginName = loginName;
		person.password = SecurityUtil.Base64Encode(password);
		person.email = email;
		person.isAvailable = true;
		
		syncOrgIn(person, OPTTYPE_ADD);
	}
	
	/**
	 * 更新OA账号信息
	 * @param id			员工ID ，fd_import_info字段
	 * @param no			工号 
	 * @param name			姓名
	 * @param mobile		手机
	 * @param tel			固话
	 * @param oa_dept_id	部门，部门的fd_import_info字段
	 * @throws Exception
	 */
	public static void updatePerson(String id,String no,String name,String gender,String mobile,String tel,String oa_dept_id) throws Exception {
		OAOrg person = new OAOrg();
		person.type = TYPE_PER;
		person.id = id;
		person.name = name;
		person.mobileNo = mobile;
//		person.workPhone = tel;
		person.parent = oa_dept_id;
		//person.no = no;
		person.sex=gender;
		person.isAvailable = true;
		
		syncOrgIn(person, OPTTYPE_UPD);
	}
	
	/**
	 * 新建部门
	 * @param id			部门ID
	 * @param no			部门编号
	 * @param name			部门名称
	 * @param parentId		上级部门
	 * @throws Exception
	 */
	public static void addDepartment(String id,String no,String name,String parentId,String adminId) throws Exception {
		OAOrg department = new OAOrg();
		department.type = TYPE_DEP;
		department.id = id;
		department.name = name;
		department.no = no;
		department.isAvailable = true;
		
		if(!StringUtil.isBlank(adminId)) {
//			adminId = "position";
			department.thisLeader = adminId;
		}
		
		
		if(StringUtil.isBlank(parentId)) {
			parentId = "company";
		}
		department.parent = parentId;
		syncOrgIn(department, OPTTYPE_ADD);
	}
	
	/**
	 * 更新部门
	 * @param id			部门ID
	 * @param no			部门编号
	 * @param name			部门名称
	 * @param parentId		上级部门
	 * @throws Exception
	 */
	public static void updateDepartment(String id,String no,String name,String parentId,String adminId) throws Exception {
		OAOrg department = new OAOrg();
		department.type = TYPE_DEP;
		department.id = id;
		department.name = name;
		//department.no = no;
		department.isAvailable = true;
		
		if(StringUtil.isBlank(adminId)) {
			adminId = "position";
		}
//		department.thisLeader = adminId;
		
		if(StringUtil.isBlank(parentId)) {
			parentId = "company";
		}
		department.parent = parentId;
		
		syncOrgIn(department, OPTTYPE_UPD);
	}
	
	/**
	 * 删除部门
	 * @param id			部门ID
	 * @param no			部门编号
	 * @param name			部门名称
	 * @param parentId		上级部门
	 * @throws Exception
	 */
	public static void deleteDepartment(String id) throws Exception {
		OAOrg department = new OAOrg();
		department.type = TYPE_DEP;
		department.isAvailable = false;
		department.id = id;
		syncOrgIn(department, OPTTYPE_DEL);
	}
	
	/**
	 * 删除员工
	 * @param id			部门ID
	 * @param no			部门编号
	 * @param name			部门名称
	 * @param parentId		上级部门
	 * @throws Exception
	 */
	public static void deletePerson(String id) throws Exception {
		OAOrg department = new OAOrg();
		department.type = TYPE_PER;
		department.isAvailable = false;
		department.id= id;
		syncOrgIn(department, OPTTYPE_DEL);
	}
	
	/**
	 * 同步组织架构信息
	 * @param orgObj  		人员或部门信息
	 * @throws Exception
	 */
	private static void syncOrgIn(OAOrg orgObj,int opType) throws Exception {
		WebServiceConfig cfg = WebServiceConfig.getInstance();

		ISysSynchroSetOrgWebService service = (ISysSynchroSetOrgWebService) callService(cfg.getAddress(), cfg.getServiceClass());
		// 请在此处添加业务代码
		SysSynchroSetOrgContext context = new SysSynchroSetOrgContext();
		context.setAppName(APPNAME);
		List<OAOrg> orgData = new ArrayList<>();
		if(OPTTYPE_ADD==opType) {
			String resultMsg = orgObj.checkAdd();
			if(!StringUtil.isBlank(resultMsg)) {
				throw new RuntimeException(resultMsg);
			}
		
		}
		
		if(OPTTYPE_UPD==opType) {
			String resultMsg = orgObj.checkUpdate();
			if(!StringUtil.isBlank(resultMsg)) {
				throw new RuntimeException(resultMsg);
			}
		}
		
		if(OPTTYPE_DEL==opType) {
			String resultMsg = orgObj.checkDelete();
			if(!StringUtil.isBlank(resultMsg)) {
				throw new RuntimeException(resultMsg);
			}
		}
		orgData.add(orgObj);
		
		String orgJsonDataStr = StringUtil.toString(orgObj,true,false);
		context.setOrgJsonData(orgJsonDataStr);
		SysSynchroSetResult result = service.updateOrgElement(context);
		int rtnSta = result.getReturnState();	//0:表示未操作。1:表示操作失败。2:表示操作成功。
		String rtnMsg = result.getMessage();
		if(rtnSta!=2) {
			throw new RuntimeException("OA组织架构同步未成功："+rtnSta+":"+rtnMsg);
		}
		
	}
	
	/**
	 * 调用服务，生成客户端的服务代理
	 * 
	 * @param address WebService的URL
	 * @param serviceClass 服务接口全名
	 * @return 服务代理对象
	 * @throws Exception
	 */
	public static Object callService(String address, Class serviceClass)
			throws Exception {

		JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
		
		// 记录入站消息
		factory.getInInterceptors().add(new LoggingInInterceptor());
		
		// 记录出站消息
		factory.getOutInterceptors().add(new LoggingOutInterceptor());
		
		// 添加消息头验证信息。如果服务端要求验证用户密码，请加入此段代码
		// factory.getOutInterceptors().add(new AddSoapHeader());

		factory.setServiceClass(serviceClass);
		factory.setAddress(address);
		
		// 使用MTOM编码处理消息。如果需要在消息中传输文档附件等二进制内容，请加入此段代码
		// Map<String, Object> props = new HashMap<String, Object>();
		// props.put("mtom-enabled", Boolean.TRUE);
		// factory.setProperties(props);		
        
        // 创建服务代理并返回
		return factory.create();
	}
	
	public static class OAOrg{
		
		private String type;		//	类型  :org(机构),dept(部门),group(群组),post(岗位),person(人员)。
		private String id;			//	集成系统中组织架构的唯一标识,不允许为空	所有组织架构类型
		private String parent;		//	设置该组织架构的父部门	org(机构),dept(部门),post(岗位),person(人员)
		private String mobileNo;	//	手机号	person(人员)
		private String email;		//	邮件地址	person(人员)
		private String workPhone;	//	办公电话	person(人员)
		private String name;		//	组织架构名称, 不允许为空	所有组织架构类型
		private String no;			//	编号,可为空	所有组织架构类型
		private String order;		//	排序号,可为空	所有组织架构类型
		private Boolean isAvailable;//	是否有效,该属性决定该组织架构是否删除	所有组织架构类型,布尔类型
		private String loginName;	//	登录名	person(人员)
		private String password;	//	密码,base64加密后的信息	person(人员)
		private String keyword;		//	关键字,可为空	所有组织架构类型
		private String memo;		//	组织架构说明,可为空	所有组织架构类型
		private String sex;			//	性别 person(人员)
		private String thisLeader;  //设置部门领导,对type为org,dept,post起作用
		private String superLeader;	//设置部门上级领导,对type为org,dept起作用
		
		public String checkAdd() throws Exception {
			String [] fieldsNotNull = null;
			if(type.equals(TYPE_PER)) {
				fieldsNotNull= new String[]{"type","id","parent","name","isAvailable","mobileNo","no","loginName","password"};
			}
			if(type.equals(TYPE_DEP)) {
				fieldsNotNull= new String[]{"type","id","name","isAvailable","no"};
			}
			
			StringBuilder rtnMsg = new StringBuilder();
			Class clazz =  this.getClass();
			for(String fieldName:fieldsNotNull) {
				Field field = clazz.getDeclaredField(fieldName);
				Object value = field.get(this);
				if(value==null || StringUtil.isBlank(value.toString())) {
					rtnMsg.append(fieldName);
					rtnMsg.append(" is null;\r\n");
				}
			}
			
			return rtnMsg.toString();
		}
		
		public String checkUpdate() throws Exception {
			String [] fieldsNotNull = new String[]{"type","id","name","isAvailable"};
			StringBuilder rtnMsg = new StringBuilder();
			Class clazz =  this.getClass();
			for(String fieldName:fieldsNotNull) {
				Field field = clazz.getDeclaredField(fieldName);
				Object value = field.get(this);
				if(value==null || StringUtil.isBlank(value.toString())) {
					rtnMsg.append(fieldName);
					rtnMsg.append(" is null;\r\n");
				}
			}
			
			return rtnMsg.toString();
		}
		
		
		public String checkDelete() throws Exception {
			
			String [] fieldsNotNull = new String[]{"type","id","isAvailable"};
			StringBuilder rtnMsg = new StringBuilder();
			Class clazz =  this.getClass();
			for(String fieldName:fieldsNotNull) {
				Field field = clazz.getDeclaredField(fieldName);
				Object value = field.get(this);
				if(value==null || StringUtil.isBlank(value.toString())) {
					rtnMsg.append(fieldName);
					rtnMsg.append(" is null;\r\n");
				}
			}
			
			return rtnMsg.toString();
		}
		
		public String getId() {
			return id;
		}
		public void setId(String id) {
			this.id = id;
		}
		public String getParent() {
			return parent;
		}
		public void setParent(String parent) {
			this.parent = parent;
		}
		public String getMobileNo() {
			return mobileNo;
		}
		public void setMobileNo(String mobileNo) {
			this.mobileNo = mobileNo;
		}
		public String getEmail() {
			return email;
		}
		public void setEmail(String email) {
			this.email = email;
		}
		public String getWorkPhone() {
			return workPhone;
		}
		public void setWorkPhone(String workPhone) {
			this.workPhone = workPhone;
		}
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public String getNo() {
			return no;
		}
		public void setNo(String no) {
			this.no = no;
		}
		public String getOrder() {
			return order;
		}
		public void setOrder(String order) {
			this.order = order;
		}
		public Boolean getIsAvailable() {
			return isAvailable;
		}
		public void setIsAvailable(Boolean isAvailable) {
			this.isAvailable = isAvailable;
		}
		public String getLoginName() {
			return loginName;
		}
		public void setLoginName(String loginName) {
			this.loginName = loginName;
		}
		public String getPassword() {
			return password;
		}
		public void setPassword(String password) {
			this.password = password;
		}
		public String getKeyword() {
			return keyword;
		}
		public void setKeyword(String keyword) {
			this.keyword = keyword;
		}
		public String getMemo() {
			return memo;
		}
		public void setMemo(String memo) {
			this.memo = memo;
		}
		public String getType() {
			return type;
		}
		public void setType(String type) {
			this.type = type;
		}

		public String getSex() {
			return sex;
		}

		public void setSex(String sex) {
			this.sex = sex;
		}

		public String getThisLeader() {
			return thisLeader;
		}

		public void setThisLeader(String thisLeader) {
			this.thisLeader = thisLeader;
		}

		public String getSuperLeader() {
			return superLeader;
		}

		public void setSuperLeader(String superLeader) {
			this.superLeader = superLeader;
		}
		
	}

}
